package org.point.common.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class AddressUtil {

	private static Log log = LogFactory.getLog(AddressUtil.class);

	private static final String URL = "http://whois.pconline.com.cn/ip.jsp?level=2";

	
	public static String getAddresses(String ip, String encodingString) {
		// 调用http://whois.pconline.com.cn的接口取得IP所在的省市信息
		// String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
		// @param level:可指定输出结果的精度，=1/=2/=3分别代表只输出省名称/输出省市名称/输出省市区名称
		// String urlStr = "http://whois.pconline.com.cn/ip.jsp?level=2";

		String returnStr = getResult(URL, "ip=" + ip, encodingString);
		if (returnStr != null && !"".equals(returnStr)
				&& !"局域网".equals(returnStr.trim())) {
			// 处理返回的省市信息
			return returnStr;
		}
		return "";
	}

	/**
	 * 请求接口返回省市信息
	 * 
	 * @param urlStr
	 *            请求的地址
	 * @param content
	 *            请求的参数 格式为：ip=0.0.0.0
	 * @param encoding
	 *            服务器端请求编码。如GBK,UTF-8等
	 * @return
	 */
	private static String getResult(String urlStr, String content,
			String encoding) {
		StringBuffer buffer = new StringBuffer();
		URL url = null;
		HttpURLConnection connection = null;
		DataOutputStream out = null;
		InputStreamReader isr = null;
		BufferedReader reader = null;
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();// 新建连接实例
			connection.setConnectTimeout(10000);// 设置连接超时时间，单位毫秒
			connection.setReadTimeout(10000);// 设置读取数据超时时间，单位毫秒
			connection.setDoOutput(true);// 是否打开输出流 true|false
			connection.setDoInput(true);// 是否打开输入流true|false
			connection.setRequestMethod("POST");// 提交方法POST|GET
			connection.setUseCaches(false);// 是否缓存true|false
			connection.connect();// 打开连接端口
			out = new DataOutputStream(connection.getOutputStream());// 打开输出流往对端服务器写数据
			out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
			out.flush();// 刷新
			out.close();// 关闭输出流
			isr = new InputStreamReader(connection.getInputStream(), encoding);
			reader = new BufferedReader(isr);// 往对端写完数据对端服务器返回数据
			// ,以BufferedReader流来读取

			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}

		} catch (IOException e) {
			log.error("AddressUtil->getResult:" + e.getMessage());
		} finally {
			try {
				if (connection != null) {
					connection.disconnect();// 关闭连接
				}
				if (out != null) {
					out.flush();// 刷新
					out.close();// 关闭输出流
				}
				if (reader != null) {
					reader.close();
				}
				if (isr != null) {
					isr.close();
				}
			} catch (Exception e) {
				log.error("AddressUtil->getResult:" + e.getMessage());
			}
		}
		return buffer.toString();
	}
}
